﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

using Teigha.DatabaseServices;
using Teigha.Geometry;
using Teigha.Colors;
using Teigha.Export_Import;
using Teigha.GraphicsInterface;
using Teigha.GraphicsSystem;
using Teigha.Runtime;

namespace ExportToDWGTool
{
    class ExportDWG
    {
        public Dictionary<string, GDSBInfo> m_DicSB = null;
        public Dictionary<string, GDXInfo> m_DicX = null;

        public Database m_pDb = null;


        public bool SaveToDWG(string strTempDWG, string strOutSave)
        {
            try
            {
                System.DateTime time = System.DateTime.Now;
                // LogManageMt.m_listLog.Add("时间：" + time.ToString() + "   开始转换，请等待……");

                if (File.Exists(strOutSave))
                {
                    File.Delete(strOutSave);
                }


                using (Database pDb = new Database(false, false))// 加参数出错
                {
                    pDb.ReadDwgFile(strTempDWG, FileOpenMode.OpenForReadAndWriteNoShare, false, "");

                    // LogManageMt.m_listLog.Add("开始将转换对象添加到模型空间，请等待……");
                    m_pDb = pDb;

                    BlockTableRecord btr = (BlockTableRecord)pDb.CurrentSpaceId.GetObject(OpenMode.ForWrite);
                    //绘制线
                    double x = 0;
                    double y = 0;

                    foreach (string key in m_DicX.Keys)
                    {
                        GDXInfo pInfo = m_DicX[key];
                        int i = 0;
                        Teigha.DatabaseServices.Polyline pLine = new Teigha.DatabaseServices.Polyline();
                        foreach (int xh in pInfo.dic.Keys)
                        {
                            GDXDInfo p = pInfo.dic[xh];

                            ConvertPlaneCoord.MCT84Bl2xy(p.lng, p.lat, out x, out y);
                            Point2d pt = new Point2d(y, x);

                            pLine.AddVertexAt(i, pt, 0, 0, 0);

                            i++;
                        }

                        ObjectId Id = btr.AppendEntity(pLine);
                        Entity pwEnt = null;
                        if (UtilityFunc.FindCADLayerByNM(pDb, "KGXL1") == true)
                        {
                            pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                            pwEnt.Layer = "KGXL1";
                        }
                                        
                        Point2d pt0 = pLine.GetPoint2dAt(0);
                        Point2d pt1 = pLine.GetPoint2dAt(1);

                        double rad = CalculateLineAngle(pt0, pt1);
                        Point3d pt3dText = new Point3d((pt0.X+pt1.X)/2, (pt0.Y + pt1.Y) / 2, 0);
                        DBText pText = CreateText(pt3dText, pInfo.strTQ+"/"+pInfo.fCD.ToString() + "米", "宋体");
                        pText.VerticalMode = TextVerticalMode.TextBottom;
                        pText.HorizontalMode = TextHorizontalMode.TextCenter;
                        pText.Height = 0.1;
                      
                        pText.Rotation = rad;

                        Id = btr.AppendEntity(pText);
                        if (UtilityFunc.FindCADLayerByNM(pDb, "GDQZJ") == true)
                        {
                            pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                            pwEnt.Layer = "GDQZJ";
                        }
                          
                    }

                    //绘制设备
                    foreach (string key in m_DicSB.Keys)
                    {
                        GDSBInfo pInfo = m_DicSB[key];

                        ObjectId BlkId = GetBlkIdByName(pDb,pInfo.strLY);
                        if(BlkId==ObjectId.Null)
                        {
                            BlkId = GetBlkIdByName(pDb, "zd");

                            pInfo.strLY = "0";
                        }

                        ConvertPlaneCoord.MCT84Bl2xy(pInfo.lng, pInfo.lat, out x, out y);
                        Point3d pt3D = new Point3d(y, x,0);

                        BlockReference blkRef = new BlockReference(pt3D, BlkId);
                        ObjectId Id = btr.AppendEntity(blkRef);
                        Entity pwEnt = null;
                        if (UtilityFunc.FindCADLayerByNM(pDb, pInfo.strLY) == true)
                        {
                            pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                            pwEnt.Layer = pInfo.strLY;
                        }   

                        if(pInfo.strLY=="GDGT")
                        {
                            BlkId = GetBlkIdByName(pDb, "zd");
                            blkRef = new BlockReference(pt3D, BlkId);
                            Id = btr.AppendEntity(blkRef);
                            if (UtilityFunc.FindCADLayerByNM(pDb, pInfo.strLY) == true)
                            {
                                pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                                pwEnt.Layer = pInfo.strLY;
                            }
                          
                        }

                    
                        if(pInfo.strLY == "GDQZJ")
                        {
                            Point3d pt3dText = new Point3d(y-1.8, x-0.3, 0);
                            DBText pText = CreateText(pt3dText, pInfo.strMC, "宋体");
                            
                            pText.HorizontalMode = TextHorizontalMode.TextRight;
                            pText.VerticalMode = TextVerticalMode.TextTop;

                            Id = btr.AppendEntity(pText);

                            if (UtilityFunc.FindCADLayerByNM(pDb, pInfo.strLY) == true)
                            {
                                pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                                pwEnt.Layer = pInfo.strLY;
                            }
                        }
                        else if(pInfo.strLY == "GDJLX")
                        {
                            Point3d pt3dText = new Point3d(y +0.35, x +0.006, 0);
                            DBText pText = CreateText(pt3dText, pInfo.strMC, "宋体");
                        
                            pText.HorizontalMode = TextHorizontalMode.TextLeft;
                            pText.VerticalMode = TextVerticalMode.TextVerticalMid;

                            Id = btr.AppendEntity(pText);
                            if (UtilityFunc.FindCADLayerByNM(pDb, pInfo.strLY) == true)
                            {
                                pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                                pwEnt.Layer = pInfo.strLY;
                            }
                        }
                        else
                        {
                            Point3d pt3dText = new Point3d(y, x + 0.8, 0);
                            DBText pText = CreateText(pt3dText, pInfo.strMC, "宋体");
                          
                            pText.HorizontalMode = TextHorizontalMode.TextMid;
                            pText.VerticalMode = TextVerticalMode.TextVerticalMid;

                            Id = btr.AppendEntity(pText);
                            if (UtilityFunc.FindCADLayerByNM(pDb, pInfo.strLY) == true)
                            {
                                pwEnt = (Entity)Id.Open(OpenMode.ForWrite);
                                pwEnt.Layer = pInfo.strLY;
                            }

                        }
                       
                    }

                    if (m_DicX.Count > 0|| m_DicSB.Count>0)
                    {
                        SaveType pSavetype = SaveType.Save12; //Save12 为.dwg Save13 为dxf

                        DwgVersion dwgver = DwgVersion.vAC21; //ACAD2010为 vAC24； ACAD2007 为 vAC21； ACAD2004为vAC18；

                        pDb.SaveAs(strOutSave, dwgver);
                    }

                    time = System.DateTime.Now;
                    // LogManageMt.m_listLog.Add("时间：" + time.ToString() + "   转换完成！"); 

                }

                return true;
            }
            catch (System.Exception ex)
            {
                System.DateTime time = System.DateTime.Now;
                // LogManageMt.m_listLog.Add("时间：" + time.ToString() + "   错误信息：" + ex.Message);
                MessageBox.Show(ex.Message);

                return false;
            }
        }

        private double CalculateLineAngle(Point2d pt1, Point2d pt2)
        {
            double J = 0;
            double x = pt2.X - pt1.X;
            double y = pt2.Y - pt1.Y;

            if (x == 0 && y < 0)
            {
                J = 0;
            }
            else
            {
                double k = y / x;
                J = Math.Atan2(y, x); //弧度
            }

            double ang = J * 180.0 / Math.PI; //角度

            if (ang < 0)
            {
                ang = ang + 360;
            }

            if (ang == 0)
            {
                ang = 270;
            }

            if (ang > 90 && ang <= 180)
            {
                ang = ang + 180;
            }
            else if (ang > 180 && ang < 270)
            {
                ang = ang - 180;
            }

            double rad = ang * Math.PI / 180;

            return rad;
        }

        private ObjectId GetTextStyleIdByName(Database pDb, string strName)
        {
            ObjectId Oid = ObjectId.Null;
            try
            {
                using (TextStyleTable styleTable = (TextStyleTable)pDb.TextStyleTableId.GetObject(OpenMode.ForRead))
                {
                    foreach (ObjectId id in styleTable)
                    {
                        using (TextStyleTableRecord pTextStyle = (TextStyleTableRecord)id.Open(OpenMode.ForRead))
                        {
                            if (pTextStyle.Name == strName)
                            {
                                Oid = id;
                                break;
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {

            }
            return Oid;
        }

        private DBText CreateText(Point3d pt, string strText, string strTextStyleName)
        {
            DBText pText = new DBText();

            pText.TextString = strText;

            ObjectId styleId = GetTextStyleIdByName(m_pDb, strTextStyleName);
            pText.TextStyleId = styleId;
            pText.Height = 0.12;
            pText.Rotation = 0;
            pText.WidthFactor = 1;
            pText.Oblique = 0;
            pText.VerticalMode = TextVerticalMode.TextVerticalMid;
            pText.HorizontalMode = TextHorizontalMode.TextCenter;

            pText.AlignmentPoint = pt;
            pText.Position = pt;

            return pText;
        }

        private ObjectId GetBlkIdByName(Database pDb, string strName)
        {
            ObjectId Oid = ObjectId.Null;
            try
            {

                TransactionManager pTMgr = pDb.TransactionManager;
                using (Transaction pTransac = pTMgr.StartTransaction())
                {
                    BlockTable pBTable = pTMgr.GetObject(pDb.BlockTableId, OpenMode.ForRead) as BlockTable;

                    foreach (ObjectId id in pBTable)
                    {

                        BlockTableRecord pBlock = pTMgr.GetObject(id, OpenMode.ForRead) as BlockTableRecord;
                        string str = pBlock.Name;
                        if (pBlock.Name == strName)
                        {
                            Oid = id;
                            break;
                        }

                        // m_Dic.Add(str, id);
                    }

                    pTransac.Commit();
                }



            }
            catch (System.Exception ex)
            {

            }
            //  m_Dic.Add("9999", Oid);
            return Oid;
        }

       
    }
}
